package com.itboye.mengwu.app.ui.mymeng;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.app.Dialog;
import android.content.Intent;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.inageview.ItemEntity;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.adapter.YuErJingAdapter;
import com.itboye.mengwu.app.ui.aiwujia.YuErJingMomDetailActivity;
import com.itboye.mengwu.app.ui.aizhiwu.ActivityQueryWodeDongTaiDetail;
import com.itboye.mengwu.app.ui.aizhiwu.GeRenActivity;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply;
import com.itboye.mengwu.data.model.TieZiModel;
import com.itboye.mengwu.data.presenter.MyTieZiCenterPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.luntan.comment.adapter.MyTieZiCommentAdapter;
import com.itboye.mengwu.luntan.comment.adapter.MyTieZiCommentReplyAdapter;
import com.itboye.mengwu.luntan.comment.bean.Reply;
import com.itboye.mengwu.widget.XListView;
import com.itboye.mengwu.widget.XListView.IXListViewListener;
import com.umeng.common.message.Log;

public class MyTieZiActivity extends BaseActivity implements Observer,
		IXListViewListener {

	// private XListView mytieXlistView;
	// private ImageView onMyonlickBack;
	// TextView care;
	// TextView question;
	// TextView question_show;
	// List<ImageView> imageViews;
	// View headerView;
	// TextView hot_talk;
	// TieZiPresenter presenter;
	// private String uid;
	// private MyAdapter adapter;
	// // AddGoodsPresenter goodsPresenter;
	// String tid;
	// private boolean isonlick = false;
	// // GoodsListModel goodsListModel;
	// int pageNo = 1;
	//
	// MyTiezibean model;
	//
	// ArrayList<TieZiModel.GetAllList.UserInfo> aLists = new
	// ArrayList<TieZiModel.GetAllList.UserInfo>();

	private Button btn_comment, btn_reply;
	private EditText edt_reply;
	private YuErJingAdapter adapter;
	private MyTieZiCommentAdapter commentAdapter;
	private MyTieZiCommentReplyAdapter commentReplyAdapter;
	private static final int ONE_COMMENT_CODE = -1;
	String type = "load";
	private ArrayList<Reply> replyList;
	RelativeLayout nodatda;
	/** Item数据实体集合 */
	private ArrayList<ItemEntity> itemEntities;
	/** ListView对象 */
	private XListView listview;
	// private RoundImage image;
	private TextView textGuan;
	private ImageView back;
	TieZiPresenter presenter;
	MyTieZiCenterPresenter presenter2;
	ArrayList<TieZiModel.GetAllList.UserInfo> arrayListUserInfo = new ArrayList<TieZiModel.GetAllList.UserInfo>();
	private LuntanTieZiBean bean;
	ArrayList<TieZiBaoHanReply.GetAList> aLists = new ArrayList<TieZiBaoHanReply.GetAList>();

	// BiaoqianPresenter biaoqianPresenter;

	@Override
	public int initView() {

		return R.layout.activity_mytiezi;
		// return R.layout.activity_gerenkongjian;
	}

	public void onMyonlickBack(View view) {
		this.finish();
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		showProgressDialog("数据加载中，请稍后", true);
		listview.setXListViewListener(this);
		listview.setPullLoadEnable(true);
		listview.setPullRefreshEnable(true);
		presenter2 = new MyTieZiCenterPresenter(this);
		aLists = new ArrayList<TieZiBaoHanReply.GetAList>();
		presenter = new TieZiPresenter(this);
		bean = new LuntanTieZiBean();
		adapter = new YuErJingAdapter(MyTieZiActivity.this, imgClickListener,
				headerClickListener, aLists, "1", deleteclick);
		listview.setAdapter(adapter);
		initCommentData();

	}

	private OnClickListener deleteclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tid = v.getTag() + "";
			showProgressDialog("删除中，请稍后", true);
			LuntanTieZiBean model = new LuntanTieZiBean();
			model.setTid(tid);
			model.setUid(uid);
			presenter.delete(model);
		}
	};

	private void initCommentData() {
		uid = SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID, "")
				+ "";
		if (SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID, "")
				+ "" != null
				|| SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID,
						"") + "" != "")
			bean.setUid((String) SPUtils.get(MyTieZiActivity.this, null,
					SpPublicParams.UID, ""));
		bean.setFid("6");
		bean.setPage_no(pageNo + "");
		presenter2.getInfo(bean);
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent2 = new Intent(MyTieZiActivity.this,
						MyTieZiDetailActivity.class);
				intent2.putExtra("tid", aLists.get(position - 1).getTid());
				startActivity(intent2);
			}
		});
	}

	OnClickListener pinglunderenclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(MyTieZiActivity.this,
					GeRenActivity.class);
			intent.putExtra(
					"uid",
					SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID,
							"") + "");
			intent.putExtra("fromUid", v.getTag() + "");
			startActivity(intent);
		}
	};

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == TieZiPresenter.TieziFenYeSuccess) {
				if (type.equals("load")) {
				} else {
					aLists.clear();
				}
				aLists.addAll(((TieZiBaoHanReply) entity.getData()).getList());
				if (aLists.size() == 0) {
					nodatda.setVisibility(View.VISIBLE);
					listview.setVisibility(View.GONE);
				} else {
					nodatda.setVisibility(View.GONE);
					listview.setVisibility(View.VISIBLE);
				}
				adapter.notifyDataSetChanged();
			} else if (entity.getEventType() == TieZiPresenter.DianzanSuccess) {
				ByAlert.alert(entity.getData() + "");
				initCommentData();
				adapter.notifyDataSetChanged();
			} else if (entity.getEventType() == TieZiPresenter.PinglunSuccess) {
				initCommentData();
			} else if (entity.getEventType() == TieZiPresenter.DeleteCommentSuccess) {
				initCommentData();
				presenter2.getInfo(bean);
				adapter.notifyDataSetChanged();
			} else if (entity.getEventType() == TieZiPresenter.DeleteCommentFail) {
				initCommentData();
				// ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == TieZiPresenter.GuanzhuSuccess) {
				initCommentData();
				// ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == TieZiPresenter.GuanzhuFail) {
				initCommentData();
				// ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == MyTieZiCenterPresenter.QueryMyTieZiSuccess) {
				if (type.equals("load")) {
				} else {
					aLists.clear();
				}
				aLists.addAll(((TieZiBaoHanReply) entity.getData()).getList());
				adapter.notifyDataSetChanged();
				// } else if (entity.getEventType() ==
				// TieZiPresenter.DianzanSuccess) {
				// initCommentData();
				// // ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == TieZiPresenter.DianzanyeFail) {
				ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == TieZiPresenter.TieziDeleteSuccess) {
				initCommentData();
				// ByAlert.alert(entity.getData() + "");
			} else if (entity.getEventType() == TieZiPresenter.TieziDeleteFail) {
				// ByAlert.alert(entity.getData() + "");
			}
			try {
				closeProgressDialog();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		stopLoad();
	}

	OnClickListener headerClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent();
			intent.putExtra("uid", uid);
			intent.putExtra("fromUid",
					aLists.get((Integer.parseInt(v.getTag() + "")))
							.getAuthorId());
			startActivity(intent);
		}
	};

	OnClickListener imgClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String tid = (String) v.getTag(R.id.tag_first);
			String isFav = (String) v.getTag(R.id.tag_second);
			if ("0".equals(isFav)) {
				showProgressDialog("请求提交中，请稍后", true);
				presenter.dianzan(uid, "1", tid);
				adapter.notifyDataSetChanged();
			} else if ("1".equals(isFav)) {
				ByAlert.alert("已经点过赞了");

			}
		}
	};

	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		uid = SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID, "")
				+ "";
		if (SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID, "")
				+ "" != null
				|| SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID,
						"") + "" != "")
			bean.setUid((String) SPUtils.get(MyTieZiActivity.this, null,
					SpPublicParams.UID, ""));
		bean.setFid("6");
		bean.setPage_no(pageNo + "");
		presenter2.getInfo(bean);
	};

	/**
	 * 发表评论的监听
	 */
	private OnClickListener addCommentListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onCreateDialog(ONE_COMMENT_CODE, ONE_COMMENT_CODE);
		}
	};

	/**
	 * 回复评论的监听（回复楼主）
	 */
	private OnClickListener replyToCommentListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int position = (Integer) v.getTag();
			onCreateDialog(ONE_COMMENT_CODE, position);
		}
	};

	/**
	 * 互相回复的监听（楼中楼）
	 */
	private OnClickListener replyToReplyListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			int parentPosition = (Integer) v.getTag(R.id.tag_first);
			int childPosition = (Integer) v.getTag(R.id.tag_second);
			String authorId = (String) v.getTag(R.id.tag_third);
			if (authorId.equals((String) SPUtils.get(MyTieZiActivity.this,
					null, SpPublicParams.UID, ""))) {
				oncreateDeleteDialog(parentPosition, childPosition, authorId);
			} else {
				onCreateDialog(parentPosition, childPosition);
			}
		}
	};

	public OnClickListener guanzhu = new OnClickListener() {

		@Override
		public void onClick(View v) {
			showProgressDialog("请求提交中,请稍后", true);
			String bUid = (String) v.getTag();
			String isFocus = (String) v.getTag(R.id.tag_first);
			System.out.println(bUid + "isFocus" + isFocus);
			if (isFocus.equals("0")) {
				presenter.guanzhu(uid, bUid, "1");
			} else {
				presenter.guanzhu(uid, bUid, "0");
			}
		}
	};

	/**
	 * 点赞监听
	 */
	private OnClickListener dianZan = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			// ByAlert.alert(v.getTag()+"");
			showProgressDialog("请求提交中，请稍后", true);
			presenter.dianzan(
					SPUtils.get(MyTieZiActivity.this, null, SpPublicParams.UID,
							"") + "", 1 + "",
					aLists.get(Integer.parseInt(v.getTag() + "")).getTid());
		}
	};
	protected String uid;
	private int pageNo;

	/**
	 * 弹出评论的对话框
	 * 
	 * @param parentPositon
	 *            父节点的position
	 * @param childPostion
	 *            子节点的position
	 * @return
	 */
	protected Dialog onCreateDialog(final int parentPositon,
			final int childPostion) {
		final Dialog customDialog = new Dialog(MyTieZiActivity.this);
		LayoutInflater inflater = MyTieZiActivity.this.getLayoutInflater();
		View mView = inflater.inflate(R.layout.dialog_comment, null);
		edt_reply = (EditText) mView.findViewById(R.id.edt_comments);
		btn_reply = (Button) mView.findViewById(R.id.btn_send);

		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		customDialog.setContentView(mView);
		customDialog.show();

		btn_reply.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (childPostion) {
				case ONE_COMMENT_CODE:
					if (TextUtils.isEmpty(edt_reply.getText().toString())) {
						Toast.makeText(MyTieZiActivity.this, "内容不能为空",
								Toast.LENGTH_SHORT).show();
					} else {
						TieZiBaoHanReply.GetAList comment = new TieZiBaoHanReply.GetAList();
					}
					break;
				default:
					if (TextUtils.isEmpty(edt_reply.getText().toString())) {
						Toast.makeText(MyTieZiActivity.this, "内容不能为空",
								Toast.LENGTH_SHORT).show();
					} else {
						showProgressDialog("数据提交中，请稍后", true);
						presenter = new TieZiPresenter(MyTieZiActivity.this);
						if (parentPositon != -1) {
							System.out.println("pid:"
									+ aLists.get(parentPositon).getReplyInfo()
											.getList().get(childPostion)
											.getPid() + "tid:"
									+ aLists.get(childPostion).getTid()
									+ "author_id:" + uid + "content:"
									+ edt_reply.getText().toString() + "to_uid"
									+ aLists.get(parentPositon).getAuthorId());
							presenter.huiFuPingLun("4",
									aLists.get(parentPositon).getReplyInfo()
											.getList().get(childPostion)
											.getPid(), aLists
											.get(parentPositon).getReplyInfo()
											.getList().get(childPostion)
											.getTid(), uid, edt_reply.getText()
											.toString(),
									aLists.get(parentPositon).getReplyInfo()
											.getList().get(childPostion)
											.getAuthorId());
							// presenter.huiFuPingLun("4", "57", "109", "153",
							// "teey", "183");

						} else {
							presenter.pinglun(
									aLists.get(childPostion).getFid(), aLists
											.get(childPostion).getTid(), aLists
											.get(childPostion).getauthorId(),
									edt_reply.getText().toString(), null,
									aLists.get(childPostion).getSubject());
						}
						initCommentData();
						customDialog.dismiss();
						edt_reply.setText("");
					}
					break;
				}
			}
		});
		return customDialog;
	}

	protected void oncreateDeleteDialog(final int parentPosition,
			final int childPosition, final String authorId) {
		// TODO Auto-generated method stub
		final Dialog customDialog = new Dialog(MyTieZiActivity.this,
				R.style.dialog);
		LayoutInflater inflater = MyTieZiActivity.this.getLayoutInflater();
		View mView = inflater.inflate(R.layout.dialog_delete_replyorcomment,
				null);
		TextView delete = (TextView) mView.findViewById(R.id.delete);
		TextView cancel = (TextView) mView.findViewById(R.id.cancel);
		// LayoutParams params=new
		// LayoutParams(getActivity().getWindowManager().getDefaultDisplay().getWidth(),100);
		// mView.setLayoutParams(params);
		customDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		customDialog.setContentView(mView);

		customDialog.show();
		delete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				customDialog.dismiss();
				showProgressDialog("数据删除中，请稍后", true);
				presenter.deletePingLun(authorId, aLists.get(parentPosition)
						.getReplyInfo().getList().get(childPosition).getFid(),
						aLists.get(parentPosition).getReplyInfo().getList()
								.get(childPosition).getTid(),
						aLists.get(parentPosition).getReplyInfo().getList()
								.get(childPosition).getPid());
			}
		});
		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				customDialog.dismiss();
			}
		});
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		pageNo = 1;
		type = "refresh";
		bean.setPage_no(pageNo + "");
		presenter2.getInfo(bean);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		pageNo++;
		type = "load";
		bean.setPage_no(pageNo + "");
		presenter2.getInfo(bean);
	}

	public void stopLoad() {
		listview.stopLoadMore();
		listview.stopRefresh();
	}
}
